package cn.xspace.app.filemg.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xspace.android.imcommon.utils.AppUtil;
import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.DateUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.xspace.app.filemg.bean.ChooseFileInfo;
import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.util.FileMg;
import cn.xspace.app.filemg.view.FileMgAdapter;
import de.greenrobot.event.EventBus;

public class FolderActivity extends Activity implements OnClickListener {
	protected TextView mImageRight;
	protected TextView mImageLeft;
	protected View mTitleLayout;
	private TextView mTitle;
	private TextView tv_file_path;
	private TextView tv_chose_size;
	private ListView mListView;
	private String PATH;
	private String LASTPATH;
	private String FROMPATH;
	private ArrayList<FileInfo> folderList = new ArrayList<FileInfo>();
	private ArrayList<FileInfo> tempList = new ArrayList<FileInfo>();
	private ArrayList<FileInfo> tempfileList = new ArrayList<FileInfo>();
	private FileMgAdapter mAdapter;
	private boolean isRun = false;
	private ChooseFileInfo chooseInfo =new  ChooseFileInfo();
	private Button btnStart;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(BaseRProxy.folder_act);
		initTopView();
		PATH = getIntent().getStringExtra("PATH");
		chooseInfo=(ChooseFileInfo) getIntent().getSerializableExtra("chooseInfo");
		FROMPATH = PATH;
		LASTPATH = PATH;
		initTextView();
	}

	protected void initTopView() {
		findViewById(BaseRProxy.r_item).setBackgroundResource(BaseRProxy.getSkinID());
		mImageLeft = (TextView) findViewById(BaseRProxy.img_left);
		mImageRight = (TextView) findViewById(BaseRProxy.img_right);
		mTitle = (TextView) findViewById(BaseRProxy.title);
		mImageRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		mImageLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		mTitle.setText("全部文件");
	}

	private void initTextView() {
		mListView = (ListView) findViewById(BaseRProxy.folder_list);
		tv_file_path= (TextView) findViewById(BaseRProxy.tv_file_path);
		tv_chose_size= (TextView) findViewById(BaseRProxy.tv_chose_size);
		btnStart= (Button) findViewById(BaseRProxy.btnStart);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				FileInfo info = folderList.get(arg2);
				if (info.isFolder()) {
					if (!isRun) {
						PATH = info.getPath();
						LASTPATH = PATH;
						updatefile();
					}
				} else {
					info.setCheckFlag(!info.isCheckFlag());
					if(info.isCheckFlag()){
						if(chooseInfo.getFileList().size()>=10){
							info.setCheckFlag(!info.isCheckFlag());
							Toast.makeText(FolderActivity.this, "最多能选10个文件", Toast.LENGTH_SHORT).show();
							return;
						}
						if((chooseInfo.getSize()+info.getSize())>(1048576*100)){
							info.setCheckFlag(!info.isCheckFlag());
							Toast.makeText(FolderActivity.this, "所选文件已超过100MB", Toast.LENGTH_SHORT).show();
							return;
						}
						chooseInfo.getFileList().add(info);	
						chooseInfo.addFileSize(info.getSize());
					}else{
					for(FileInfo cInfo: chooseInfo.getFileList()){
						if(cInfo.getPath().equals(info.getPath())){
							chooseInfo.removeFileSize(info.getSize());
							chooseInfo.getFileList().remove(cInfo);
							break;
						}
					}
					}
					mAdapter.notifyDataSetChanged();
					tv_chose_size.setText(FileMg.FormetFileSize(chooseInfo.getSize()));
					initStartBtnText();
				}
			}
		});
		tv_chose_size.setText(FileMg.FormetFileSize(chooseInfo.getSize()));
		initStartBtnText();
		tv_file_path.setText(PATH);
		updatefile();
	}

	@Override
	public void onDestroy() {

		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == BaseRProxy.btnStart) {
			/*if(!AppUtil.isConnected(getBaseContext())){
				Toast.makeText(this, "当前网络未连接,请检查网络连接后重试", Toast.LENGTH_SHORT).show();
			}
			else*/ if(chooseInfo.getFileList().size()==0){
				Toast.makeText(this, "请选择文件", Toast.LENGTH_SHORT).show();
			}else{
//				Intent mIntent = new Intent();
//				mIntent.putExtra("chooseInfo", chooseInfo);
//				mIntent.putExtra("isSend", true);
//				setResult(RESULT_OK, mIntent);
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("type","FolderActivity");
				map.put("chooseInfo", chooseInfo);
				map.put("isSend", true);
				EventBus.getDefault().post(map);
				finish();
			}

		}

	}

	private void updatefile() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					if (isRun) {
						return;
					}
					File f = new File(PATH);
					isRun = true;
					if (f != null) {
						tempList.clear();
						tempfileList.clear();
						if (!LASTPATH.equals(FROMPATH)) {
							LASTPATH = f.getParentFile().getPath();
						}

						for (File file : f.listFiles()) {
							FileInfo info = new FileInfo();
							info.setPath(file.getPath());
							info.setName(file.getName());
							if (info.getName().startsWith(".")) {
								continue;
							}
							info.setFolder(true);
							if (file.isFile()) {
								info.setFileType(file.getName().substring(
										file.getName().indexOf(".") + 1,
										file.getName().length()));
								info.setPackageName(file.getParent());
								info.setSize(FileMg.getFileSizes(file));
								info.setFolder(false);
								info.setTime(DateUtils
										.timeMillisToDateTimeString(
												file.lastModified(),
												DateUtils.FORMAT_5));
								for(FileInfo cInfo: chooseInfo.getFileList()){
									if(cInfo.getPath().equals(info.getPath())){
										info.setCheckFlag(true);
									}
								}
								tempfileList.add(info);
							} else {
								tempList.add(info);
							}
						}
					}
					handler.sendEmptyMessage(0);
				} catch (Exception e) {
					System.out.println("-----------------------e:"
							+ e.getMessage());
					e.printStackTrace();
				} finally {
					isRun = false;
				}
			}

		}).start();

	}

	@Override
	public void onBackPressed() {
		if (!FROMPATH.equals(PATH)) {
			if (!isRun) {
				PATH = LASTPATH;
				folderList.clear();
				handler.sendEmptyMessage(0);
				updatefile();
			}
		} else {
//			Intent mIntent = new Intent();
//			mIntent.putExtra("chooseInfo", chooseInfo);
//			setResult(RESULT_OK, mIntent);
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("type","FolderActivity");
			map.put("chooseInfo", chooseInfo);
			EventBus.getDefault().post(map);
			finish();
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				tv_file_path.setText(PATH);
				if (!LASTPATH.equals(FROMPATH)) {
					mImageLeft.setText("返回上一级");
				} else {
					mImageLeft.setText("全部文件");
				}
				folderList.clear();
				folderList.addAll(tempList);
				folderList.addAll(tempfileList);
				if (mAdapter != null) {
					try {
						mAdapter.notifyDataSetChanged();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					mAdapter = new FileMgAdapter(FolderActivity.this,
							folderList);
					mListView.setAdapter(mAdapter);
				}
				break;
			case 1:
				break;

			default:
				break;
			}
		}
	};
	
	private void initStartBtnText() {
		if (chooseInfo.getFileList().size() > 0) {
			btnStart.setText("发送(" + chooseInfo.getFileList().size() + ")");
		} else {
			btnStart.setText("发送");
		}

	}
}
